import type { ReactNode } from 'react'
import React, { forwardRef, memo, useImperativeHandle, useRef } from 'react'
import { FormInstance, Modal } from 'antd'
import { IModalConfig } from '@/components/page-modal/type'
import BaseForm, { IBaseFormComponentRef } from '../base-form'

interface IProps {
  children?: ReactNode
  open: boolean
  onConfirm: (form: FormInstance | undefined) => void
  onCancel: (form: FormInstance | undefined) => void
  modalConfig: IModalConfig
}

export interface IBaseModalRef {
  getFormInstance: () => FormInstance<any> | undefined
  updateFormView: (values: any) => void
}

const BaseModal = (props: IProps, ref: any) => {
  const { modalConfig, open, onConfirm, onCancel } = props
  const baseForm = useRef<IBaseFormComponentRef>(null)

  function handleOk() {
    const form = baseForm.current?.getFormInstance()
    onConfirm(form)
  }

  function handleCancel() {
    const form = baseForm.current?.getFormInstance()
    onCancel(form)
  }

  // 向外暴露方法
  useImperativeHandle(ref, () => ({
    getFormInstance() {
      return baseForm.current?.getFormInstance()
    },
    updateFormView(values: any) {
      baseForm.current?.updateFormView(values)
    }
  }))

  return (
    <Modal
      {...modalConfig.modalProps}
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <BaseForm ref={baseForm} config={modalConfig.formProps}>
        {props.children}
      </BaseForm>
    </Modal>
  )
}

export default memo(forwardRef(BaseModal))
